package com.chwl.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.StringUtils;

public class ObjectMapperUtil {

	//定义常量对象
	// 优势1: 对象独一份节省空间
	// 优势2: 对象不允许别人随意篡改
	private static final ObjectMapper objectMapper = new ObjectMapper();

	/**
	 * 1.将任意对象转化为JSON
	 * 1)使用Object对象来接
	 * 2)返回值是JSON串->String类型
	 * 3)使用什么方法转化JSON	FASTJSON/ObjectMapper
	 */
	public static String getJson(Object object) {

		try {
			if (object == null)
				throw new RuntimeException("传递的参数为空");
			String json = objectMapper.writeValueAsString(object);
			return json;
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			//应该将检查异常,转化为运行时异常
			throw new RuntimeException("转化失败,传递的对象不支持json转化/检查是否有get/set方法");
		}
	}

	//2.将任意JSON串转化为对象  传递什么类型转化什么对象
	public static <T> T getObject(String json, Class<T> target) {
		try {
			if (StringUtils.isEmpty(json) || target == null)
				throw new RuntimeException("传递的参数为空");
			T t = objectMapper.readValue(json, target);
			return t;
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			throw new RuntimeException("转化失败,传递的对象不支持json转化/检查是否有get/set方法");
		}
	}
}
